//
//  KTCaptchaButton.m
//  button
//
//  Created by yushanchang on 15/10/24.
//  Copyright © 2015年 yushanchang. All rights reserved.
//

#import "BVCaptchaButton.h"
#define CAPTCHA_TIMEOUT 1.0

@interface BVCaptchaButton ()

@property (nonatomic, strong) NSTimer *buttonTextTimer;
@property (nonatomic) NSUInteger captchaButtonText;
@property (nonatomic) NSUInteger initialButtonText;

@end

@implementation BVCaptchaButton

- (void)setCountdown:(NSUInteger)countdownTime {
    
    _captchaButtonText = countdownTime;
    _initialButtonText = countdownTime;
    [self addTarget:self action:@selector(sendCaptcha:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)sendCaptcha:(BVCaptchaButton *)sender {
    [self startButtonTextTimer];
    sender.userInteractionEnabled = NO;
    _buttonTextTimer = [NSTimer scheduledTimerWithTimeInterval: CAPTCHA_TIMEOUT target:self selector:@selector(startButtonTextTimer) userInfo:nil repeats:YES];
}

- (void)startButtonTextTimer {
    
    if (_captchaButtonText > 0) {
        [UIView performWithoutAnimation:^{
            [self setTitle:[NSString stringWithFormat:@"%ld%@", _captchaButtonText, @"秒"] forState:UIControlStateNormal];
            [self layoutIfNeeded];
        }];
    }else {
        [UIView performWithoutAnimation:^ {
            [self setTitle: @"重新发送" forState:UIControlStateNormal];
            [self layoutIfNeeded];
        }];
        [_buttonTextTimer invalidate];
        self.userInteractionEnabled = YES;
        _captchaButtonText = _initialButtonText;
    }
    _captchaButtonText--;
}

@end
